import { FC, ReactElement } from 'react'
import React from 'react'
import { NewItem } from 'Src/typings/interface'

import style from './index.scss'

interface IProps {
  // children: React.ReactChild
  item: NewItem
}

const Info = (item: NewItem) => (
  <div className={style['info']}>
    <span className={style['author']}>{item.author_name}</span>
    <span className={style['date']}>{item.date}</span>
  </div>
)

const PicItem: FC<{ item: NewItem; children: any }> = ({ children, item }): ReactElement => {
  return (
    <>
      <div className={style['main']}>
        <div className={style['title']}>
          <h1>{item.title}</h1>
        </div>
        {children && children(item)}
      </div>
      <Info {...item} />
    </>
  )
}

const Img: FC<{ pic: string; title: string; last?: string }> = ({ pic, title, last }) => {
  return (
    <div className={`${style['img']} ${last ? last : ''}`}>
      <img onLoad={(e) => ((e.target as HTMLImageElement).style.opacity = '1')} src={pic} alt={title} />
    </div>
  )
}

const getChildren = (item: NewItem): JSX.Element => {
  const { thumbnail_pic_s, thumbnail_pic_s02, thumbnail_pic_s03 } = item

  switch (true) {
    // 0 张图片的布局
    case !thumbnail_pic_s:
      return (
        <div className={`${style['news-item']} ${style['type-0']}`}>
          <Info {...item} />
        </div>
      )
    // 一张图片的布局
    case thumbnail_pic_s && !thumbnail_pic_s02:
      return (
        <div className={`${style['news-item']} ${style['type-1']}`}>
          <PicItem item={item}>
            {(item: NewItem) => (
              <div className={`${style['pic']}`}>
                <Img pic={item.thumbnail_pic_s} title={item.title} />
              </div>
            )}
          </PicItem>
        </div>
      )
    case thumbnail_pic_s02 && !thumbnail_pic_s03:
      return (
        <div className={`${style['news-item']} ${style['type-2']}`}>
          <PicItem item={item}>
            {(item: NewItem) => (
              <div className={`${style['pic']}`}>
                <Img pic={item.thumbnail_pic_s} title={item.title} />
                <Img pic={item.thumbnail_pic_s02} title={item.title} last={style['last']} />
              </div>
            )}
          </PicItem>
        </div>
      )
    case !!thumbnail_pic_s03:
      return (
        <div className={`${style['news-item']} ${style['type-3']}`}>
          <PicItem item={item}>
            {(item: NewItem) => (
              <div className={style['pic']}>
                <Img pic={item.thumbnail_pic_s} title={item.title} />
                <Img pic={item.thumbnail_pic_s02} title={item.title} />
                <Img pic={item.thumbnail_pic_s03} title={item.title} last={style['last']} />
              </div>
            )}
          </PicItem>
        </div>
      )
    default:
      return <></>
  }
}

const NewsItem: FC<IProps> = ({ item }): ReactElement => {
  const children = getChildren(item)

  return children
}

export default NewsItem
